package cdp.tarasenko.epamevospring.service;

import cdp.tarasenko.epamevospring.model.CityDataBean;
import cdp.tarasenko.epamevospring.model.CityGeoLocation;
import cdp.tarasenko.epamevospring.model.QuarterEvoData;
import cdp.tarasenko.epamevospring.repository.EvoDataRepository;
import cdp.tarasenko.epamevospring.repository.GeoLocationRepository;
import com.google.code.geocoder.Geocoder;
import com.google.code.geocoder.GeocoderRequestBuilder;
import com.google.code.geocoder.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Oleksandr_Tarasenko
 */
@Service
public class MapDataService {

    @Autowired
    protected GeoLocationService geoLocationService;

    @Autowired
    protected GeoLocationRepository geoLocationRepository;

    @Autowired
    protected EvoDataRepository evoDataRepository;

    public Map<String, Object> getCitiesLocationByQuarter(int quarter) {
        Map<String, Object> result = new HashMap<String, Object>();

        QuarterEvoData quarterData = evoDataRepository.findEvoDataByQuarter(quarter);
        if (quarterData == null) {
            return result;
        }
        List<QuarterEvoData.CityEvoData> cities = quarterData.getCities();

        List<CityDataBean> citiesData  = new ArrayList<CityDataBean>(cities.size());

        for (QuarterEvoData.CityEvoData city : cities){
            String cityName = city.getCity();
            CityGeoLocation geoData = geoLocationRepository.findCityLocationByName(cityName);
            if (geoData == null) {
                geoData = geoLocationService.getLocationFromGoogleGeocode(cityName);
                geoLocationRepository.save(geoData);
            }
            citiesData.add(new CityDataBean(cityName, city.getEmployees(), geoData.getPos().getLatitude(), geoData.getPos().getLongitude()));
        }

        result.put("cities", citiesData);
        result.put("year", quarterData.getYear());
        result.put("quarter", quarterData.getQuarter());
        return result;
    }

}
